package com.os.messageConverter;

import com.os.domain.DemoObj;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Author Matt
 * @Date 2022-01-17
 * @Desc:
 * @Version V1.0
 */
//集成接口，实现自定义httpmessageConverter
public class MyMessageConverter extends AbstractHttpMessageConverter<DemoObj> {

    public MyMessageConverter(){
        super(new MediaType("application", "x-wisely", Charset.forName("UTF-8")));  //新建一个我们自定义的媒体类型application/x-wisely
    }

    //表明HttpMessageConverter只处理DemoObj这个类
    @Override
    protected boolean supports(Class<?> aClass) {
        return DemoObj.class.isAssignableFrom(aClass);
    }

    //重写readInternal方法，处理请求的数据。代码表明我么处理“-”隔离开的数据，并转换成DemoObj对象
    @Override
    protected DemoObj readInternal(Class<? extends DemoObj> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String temp = StreamUtils.copyToString(httpInputMessage.getBody(),
                Charset.forName("UTF-8"));

        String[] tempArr = temp.split("-");
        return new DemoObj(new Long(tempArr[0]), tempArr[1]);
    }

    //重写writeInternal，处理如何输出数据到response。该案例中，我们在原输出前面加上"hello:"
    @Override
    protected void writeInternal(DemoObj obj, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        String out = "hello:" + obj.getId() + "-" + obj.getName();
        httpOutputMessage.getBody().write(out.getBytes());
    }


}
